package com.yc.chatroom.server.service;

import javax.transaction.Transactional;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yc.chatroom.common.dto.ResultDto;
import com.yc.chatroom.common.dto.RegisterDto;
import com.yc.chatroom.server.dao.UserRepositoryDao;
import com.yc.chatroom.server.pojo.LoginStatus;
import com.yc.chatroom.server.pojo.po.UserPo;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

import java.util.Date;
import java.util.List;

@Service
public class UserService {
	
	private static final Log log = LogFactory.get();
	
	@Autowired
	private UserRepositoryDao userRepositoryDao;


	@Transactional
	public ResultDto register(RegisterDto dto) {
		log.info("----register--{}", dto.getAccount());
		UserPo user = new UserPo();
		user.setUserAccount(dto.getAccount());
		user.setUserPassword(dto.getPassword());
		user.setUserName(dto.getName());

		userRepositoryDao.save(user);
		
		return new ResultDto("注册成功");
	}

	@Transactional
	public void setLoginTime(Integer userId) {
		userRepositoryDao.updateLastLoginTime(userId, new Date().getTime());
	}
	
	@Transactional
	public void updateLogStatus(UserPo oldUserInfo, LoginStatus loginStatus) {
		UserPo newUserInfo = new UserPo();
		BeanUtils.copyProperties(oldUserInfo, newUserInfo, "userPhoto");;
		newUserInfo.setUserOnlineStatus(loginStatus.getId());
		Long now = new Date().getTime();
		if (LoginStatus.LOGIN.equals(loginStatus)) {//成功登录：更新登录状态，更新登录时间
			newUserInfo.setUserLastLoginTime(now);
		} else if (LoginStatus.LOGOUT.equals(loginStatus)) {//登出：更新登录状态，更新登出时间
			newUserInfo.setUserLastLogoutTime(now);
		}
		
		newUserInfo.setLastModifyTime(now);
		userRepositoryDao.save(newUserInfo);
	}
	
	
	public List<UserPo> get() {
		return userRepositoryDao.findAll();
	}
}
